import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

public class PoolConnectionHandler implements Runnable{

	protected Socket connection;
	protected static List<Socket> pool = new LinkedList<Socket>();

	/**
	 * @param requestToHandler
	 * 每接收一个请求就在池中增加一个socket
	 * 并通知所有等待的进程
	 */
	public static void processRequest(Socket requestToHandler) {
		synchronized (pool) {
			pool.add(pool.size(), requestToHandler);
			pool.notifyAll();
		}

	}

	public void handleConnection()
	{
		System.out.println(Thread.currentThread().getName() + "handler" + connection) ;
		PrintWriter writer = null;
		try {
			writer = new PrintWriter(connection.getOutputStream()) ;
			writer.write(Thread.currentThread().getName() + "handle me" + connection.getPort());
			writer.flush() ;
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			writer.close() ;
		}
	}


	@Override
	public void run()
	{

		/*
		 * 此处while true循环是必须的
		 * 否则该对象实例将会消失，达不到连接池的效果
		 * 
		 */
		while(true)
		{
			synchronized(pool){
				while(pool.isEmpty()){
					try {
						pool.wait() ;
					} catch (InterruptedException e) {
						e.printStackTrace();
						return ;
					}
				}
				connection = pool.remove(0) ;
			}

			handleConnection() ;

		}
	}

}